package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.DaiBi;
import cn.pugle.oj.catalog.Unknown;

import java.util.*;

/**
 * https://leetcode.com/problems/group-anagrams/
 * 第一个想法, 每个字符串都内部排序, 然后用map分组
 *
 * @author tzp
 * @since 2020/10/18
 */
public class LC49 implements DaiBi {

    //Input: strs = ["eat","tea","tan","ate","nat","bat"]
    //Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
    //1 <= strs.length <= 104
    //0 <= strs[i].length <= 100
    //strs[i] consists of lower-case English letters.
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();//key是排序后的, v是原始string
        for (String str : strs) {
            char[] a = str.toCharArray();
            Arrays.sort(a);
            map.compute(new String(a),
                    (k, oldValue) -> {
                        if (oldValue == null) oldValue = new ArrayList<>();
                        oldValue.add(str);
                        return oldValue;
                    });
        }
        return new ArrayList<>(map.values());
    }

    public static void main(String[] args) {
        String[] a = {"eat", "tea", "tan", "ate", "nat", "bat", "baa", "aab"};
        System.out.println(new LC49().groupAnagrams(a));
    }
}
